﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using System.Diagnostics;

namespace IdeasFree.SharePoint.StsAdm.Logger
{
    /// <summary>
    /// EventLogger
    /// </summary>
    public class EventLogger : ILogger
    {
        const string eventSource = "IdeasFree.SharePoint";

        
        #region ILogger Members

        public void Log(Exception ex, EventLogEntryType eventType)
        {
            Log("Message  : {0}.\r\nStackTrace  : {1}", eventType, ex.Message, ex.StackTrace);
        }

        public void Log(string message, EventLogEntryType eventType, params string[] args)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                if (!EventLog.Exists(eventSource))
                {
                    try
                    {
                        EventLog.CreateEventSource(eventSource, eventSource);
                    }
                    catch { }
                }

                if (EventLog.Exists(eventSource))
                    EventLog.WriteEntry(eventSource, String.Format(message, args), eventType);
                else
                    EventLog.WriteEntry("Application", String.Format(message, args), eventType);
            }
            );
        }

        void ILogger.Log(string message, Exception ex, EventLogEntryType eventType)
        {
            Log("{0}\r\nMessage  : {1}.\r\nStackTrace  : {2}", eventType, message, ex.Message, ex.StackTrace);
        }

        #endregion
    }
}
